from observer import Observee

class NetworkManagerObservee(Observee):

    def __init__(self):
        super(NetworkManagerObservee, self).__init__()
        self.connected = True
        self.enabled = True
        self.error = None
        self.__init()

    def set_status(self, enabled, error=None):
        assert enabled or error is not None
        self.enabled, self.error = (enabled, error)

    def set_connected(self, connected):
        self.connected = connected
        self.notify()

    def __init(self):
        try:
            import dbus
        except ImportError:
            self.set_status(False, _('Python DBus binding is not installed.'))
            self.set_connected(True)
        else:
            import dbus.mainloop.glib
            dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

            try:
                proxy = dbus.SystemBus().get_object(
                    'org.freedesktop.NetworkManager',
                    '/org/freedesktop/NetworkManager')
            except dbus.DBusException:
                self.set_status(False, _('Could not connect to NetworkManager. It is probably not installed.'))
                self.set_connected(True)
            else:
                self.set_status(True)

                def state_changed(state):
                    self.set_connected(state == 3)
                state_changed(dbus.Interface(proxy, 'org.freedesktop.DBus.Properties').Get('org.freedesktop.NetworkManager', 'State'))
                proxy.connect_to_signal('StateChanged', state_changed)
